class Login{
    constructor(){
        this.user=$("#user");
        this.pwd=$("#pwd");
        this.login=$(".login");
        this.error=$(".error");
        this.toast=$(".toast");
        this.msg=$(".msg")
        this.url="http://api.icodeilife.cn:81/user";
        this.addEvent();
    }
    addEvent(){
        this.login.on("click",()=>{
            this.u=this.user.val();
            this.p=this.pwd.val();
            this.go();
        });
        this.msg.on("click",()=>{
            location.href="register.html";
        })
        document.onkeydown=(eve)=>{
            var e=eve||window.event;
            var code=e.which||e.keyCode;
            if(code==13){
                this.login.click();
            }
        }
        
    }
    go(){
        $.ajax({
            url:this.url,
            data:{
                type:"login",
                user: this.u,
                pass: this.p
            },
            success:(res)=>{
                this.obj=JSON.parse(res);
                console.log(this.obj);
                if(this.u&&this.p){
                    switch(this.obj.code){
                        case 0:
                            this.error.css("display","block");
                            break;
                        case 1: 
                            this.error.css("display","none");
                            this.toast.css({
                                "background":"green",
                                "opacity":"1"
                            });
                            this.toast.html("登录成功");
                            setTimeout(() => {
                                this.toast.css({
                                    "opacity":"0"
                                });
                            }, 2000);
                            sessionStorage.setItem("user",JSON.stringify(this.obj.msg));
                            location.href="../index.html";
                            break;
    
                        case 2:
                            this.error.css("display","block");
                    }

                }else{
                    this.error.css("display","block");

                }
                
            }
        })
    }
     
}
new Login();